package co.yixiang.modules.system.service.impl;

import co.yixiang.modules.shop.service.YxUserService;
import co.yixiang.modules.system.domain.User;
import co.yixiang.modules.system.domain.UserShop;
import co.yixiang.modules.system.repository.UserRepository;
import co.yixiang.modules.system.service.UserService;
import co.yixiang.modules.utils.MapUtils;
import co.yixiang.utils.ValidationUtil;
import co.yixiang.utils.FileUtil;
import co.yixiang.modules.system.repository.UserShopRepository;
import co.yixiang.modules.system.service.UserShopService;
import co.yixiang.modules.system.service.dto.UserShopDto;
import co.yixiang.modules.system.service.dto.UserShopQueryCriteria;
import co.yixiang.modules.system.service.mapper.UserShopMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import co.yixiang.utils.PageUtil;
import co.yixiang.utils.QueryHelp;

import java.util.*;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
* @author lijuhunze
* @date 2020-04-28
*/
@Service
//@CacheConfig(cacheNames = "userShop")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserShopServiceImpl implements UserShopService {

    private final UserShopRepository userShopRepository;

    private final UserShopMapper userShopMapper;

    private final UserService userService;
    @Autowired
    private YxUserService yxUserService;

    @Resource
    private UserRepository userRepository;

    public UserShopServiceImpl(UserShopRepository userShopRepository, UserShopMapper userShopMapper, UserService userService) {
        this.userShopRepository = userShopRepository;
        this.userShopMapper = userShopMapper;
        this.userService = userService;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserShopDto createShopper(UserShop resources) {
        long uid = yxUserService.create(resources.getUser()).getUid();
        userShopRepository.updateUidById(resources.getId(),uid);
        return findById(resources.getId());
    }

    @Override
    //@Cacheable
    public Map<String,Object> queryAll(UserShopQueryCriteria criteria, Pageable pageable){

        Page<UserShop> page = userShopRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);

        List<UserShop> content = page.getContent();
        ArrayList<Object> objects = new ArrayList<>();
        for (UserShop userShop : content) {
            Map<String, Object> map = MapUtils.entityToMap(userShop);
            try {
                Long id = userShop.getId();
                Optional<User> byId = userRepository.findById(id);
                map.put("user",byId.get());
            } catch (Exception e) {
                map.put("user",null);
            }
            objects.add(map);
        }
        return PageUtil.toPage(objects,page.getTotalElements());
    }

    @Override
    //@Cacheable
    public List<UserShopDto> queryAll(UserShopQueryCriteria criteria){
        return userShopMapper.toDto(userShopRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    //@Cacheable(key = "#p0")
    public UserShopDto findById(Long id) {
        UserShop userShop = userShopRepository.findById(id).orElseGet(UserShop::new);
        ValidationUtil.isNull(userShop.getId(),"UserShop","id",id);
        return userShopMapper.toDto(userShop);
    }

    @Override
    //@CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public UserShopDto create(UserShop resources) {
        return userShopMapper.toDto(userShopRepository.save(resources));
    }

    @Override
    //@CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(UserShop resources) {
        UserShop userShop = userShopRepository.findById(resources.getId()).orElseGet(UserShop::new);
        ValidationUtil.isNull( userShop.getId(),"UserShop","id",resources.getId());
        userShop.copy(resources);
        userShopRepository.save(userShop);
    }

    @Override
    //@CacheEvict(allEntries = true)
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            userShopRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<UserShopDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (UserShopDto userShop : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户ID", userShop.getUser());
            map.put("商户所在省", userShop.getProvince());
            map.put("商户所在市", userShop.getCity());
            map.put("商户所在区", userShop.getDistrict());
            map.put("商户详细地址", userShop.getAddress());
            map.put("商户名称", userShop.getMerchantName());
            map.put(" linkUser",  userShop.getLinkUser());
            map.put("商户电话", userShop.getLinkTel());
            map.put("商户证书", userShop.getCharter());
            map.put("添加时间", userShop.getAddTime());
            map.put("审核时间", userShop.getApplyTime());
            map.put("通过时间", userShop.getSuccessTime());
            map.put("未通过原因", userShop.getFailMessage());
            map.put("未通过时间", userShop.getFailTime());
            map.put("-1 审核未通过 0未审核 1审核通过", userShop.getStatus());
            map.put("身份证正面", userShop.getIdFont());
            map.put("身份证反面", userShop.getIdReverse());
            map.put("0 = 开启 1= 关闭", userShop.getIsLock());
            map.put("是否删除", userShop.getIsDel());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}